<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>激活码管理</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
    />
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  </head>
  <body>
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
      <div class="container-fluid">
        <a class="navbar-brand" href="#">授权后台</a>
        <div class="d-flex">
          <a class="btn btn-outline-light btn-sm" href="/admin/logout">退出</a>
        </div>
      </div>
    </nav>

    <div class="container my-4">
      <div class="d-flex justify-content-between align-items-center mb-3">
        <h2 class="h4">激活码列表</h2>
        <form method="get" action="/admin/dashboard" class="d-flex" style="width: 300px;">
          <input class="form-control form-control-sm me-2" type="search" name="q" placeholder="搜索激活码或备注" value="{{ search_query }}">
          <button class="btn btn-outline-secondary btn-sm" type="submit">搜索</button>
        </form>
        <div>
          <button class="btn btn-danger btn-sm me-2" id="batchDeleteBtn" style="display: none;">批量删除</button>
          <a class="btn btn-success btn-sm" href="/admin/codes/export">导出全部</a>
          <a class="btn btn-secondary btn-sm" href="/admin/codes/export?unused=true">导出未激活</a>
        </div>
      </div>
      <div class="table-responsive">
        <table class="table table-striped table-sm align-middle">
          <thead class="table-light">
            <tr>
              <th><input type="checkbox" id="selectAll" class="form-check-input"></th>
              <th>ID</th>
              <th>激活码</th>
              <th>Quota</th>
              <th>已用</th>
              <th>启用</th>
              <th>备注</th>
              <th>创建</th>
              <th>剩余有效期</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            {% for c in codes %}
            <tr>
              <td><input type="checkbox" class="form-check-input code-checkbox" data-id="{{ c.id }}"></td>
              <td>{{ c.id }}</td>
              <td>{{ c.raw_code }}</td>
              <td>{{ c.quota }}</td>
              <td>{{ c.used }}</td>
              <td>
                {% if c.enabled %}
                <span class="badge bg-success">Yes</span>
                {% else %}
                <span class="badge bg-secondary">No</span>
                {% endif %}
              </td>
              <td>{{ c.comment }}</td>
              <td>{{ c.created_at }}</td>
              <td>
                {% if c.used > 0 and c.expires_at %}
                  {{ get_remaining_time_str(c.expires_at) }}
                {% else %}
                  -
                {% endif %}
              </td>
              <td>
                <div class="d-flex gap-1">
                  <button
                    class="btn btn-outline-primary btn-sm"
                    data-bs-toggle="modal"
                    data-bs-target="#quotaModal"
                    data-id="{{ c.id }}"
                    data-quota="{{ c.quota }}"
                  >修改配额</button>
                  {% if c.enabled %}
                  <form method="post" action="/admin/code/{{ c.id }}/disable" style="display: inline;" onsubmit="return confirm('确认禁用?')">
                    <button class="btn btn-outline-danger btn-sm" type="submit">禁用</button>
                  </form>
                  {% endif %}
                  <form method="post" action="/admin/code/{{ c.id }}/delete" style="display: inline;" onsubmit="return confirm('确认删除此激活码？删除后无法恢复！')">
                    <button class="btn btn-danger btn-sm" type="submit">删除</button>
                  </form>
                </div>
              </td>
            </tr>
            {% endfor %}
          </tbody>
        </table>
      </div>

      <!-- Pagination -->
      {% if total_pages > 1 %}
      <nav aria-label="Page navigation">
        <ul class="pagination justify-content-center">
          <li class="page-item {% if current_page == 1 %}disabled{% endif %}">
            <a class="page-link" href="?page={{ current_page - 1 }}&q={{ search_query }}">上一页</a>
          </li>
          {% for p in range(1, total_pages + 1) %}
            <li class="page-item {% if p == current_page %}active{% endif %}">
              <a class="page-link" href="?page={{ p }}&q={{ search_query }}">{{ p }}</a>
            </li>
          {% endfor %}
          <li class="page-item {% if current_page == total_pages %}disabled{% endif %}">
            <a class="page-link" href="?page={{ current_page + 1 }}&q={{ search_query }}">下一页</a>
          </li>
        </ul>
      </nav>
      {% endif %}

    </div>

    <!-- Quota Modal -->
    <div class="modal fade" id="quotaModal" tabindex="-1" aria-hidden="true">
      <div class="modal-dialog">
        <form class="modal-content" method="post" id="quotaForm">
          <div class="modal-header">
            <h5 class="modal-title">修改配额</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label for="new_quota" class="form-label">新的配额</label>
              <input type="number" class="form-control" name="new_quota" id="new_quota" min="1" required />
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
            <button type="submit" class="btn btn-primary">保存</button>
          </div>
        </form>
      </div>
    </div>

    <script>
      const quotaModal = document.getElementById('quotaModal');
      quotaModal.addEventListener('show.bs.modal', event => {
        const button = event.relatedTarget;
        const id = button.getAttribute('data-id');
        const quota = button.getAttribute('data-quota');
        const form = document.getElementById('quotaForm');
        form.action = `/admin/code/${id}/quota`;
        document.getElementById('new_quota').value = quota;
      });

      // 全选/取消全选功能
      const selectAllCheckbox = document.getElementById('selectAll');
      const codeCheckboxes = document.querySelectorAll('.code-checkbox');
      const batchDeleteBtn = document.getElementById('batchDeleteBtn');

      selectAllCheckbox.addEventListener('change', function() {
        codeCheckboxes.forEach(checkbox => {
          checkbox.checked = this.checked;
        });
        updateBatchDeleteButton();
      });

      // 单个复选框变化时更新全选状态和批量删除按钮
      codeCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function() {
          updateSelectAllCheckbox();
          updateBatchDeleteButton();
        });
      });

      function updateSelectAllCheckbox() {
        const checkedCount = document.querySelectorAll('.code-checkbox:checked').length;
        selectAllCheckbox.checked = checkedCount === codeCheckboxes.length && codeCheckboxes.length > 0;
        selectAllCheckbox.indeterminate = checkedCount > 0 && checkedCount < codeCheckboxes.length;
      }

      function updateBatchDeleteButton() {
        const checkedCount = document.querySelectorAll('.code-checkbox:checked').length;
        batchDeleteBtn.style.display = checkedCount > 0 ? 'inline-block' : 'none';
        if (checkedCount > 0) {
          batchDeleteBtn.textContent = `批量删除 (${checkedCount})`;
        }
      }

      // 批量删除功能
      batchDeleteBtn.addEventListener('click', async function() {
        const checkedBoxes = document.querySelectorAll('.code-checkbox:checked');
        const codeIds = Array.from(checkedBoxes).map(cb => parseInt(cb.getAttribute('data-id')));
        
        if (codeIds.length === 0) {
          alert('请选择要删除的激活码');
          return;
        }

        if (!confirm(`确定要删除选中的 ${codeIds.length} 个激活码吗？删除后无法恢复！`)) {
          return;
        }

        try {
          const response = await fetch('/admin/codes/batch-delete', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(codeIds)
          });

          if (response.ok) {
            const result = await response.json();
            alert(`成功删除 ${result.deleted_count} 个激活码`);
            window.location.reload();
          } else {
            alert('删除失败，请重试');
          }
        } catch (error) {
          console.error('Error:', error);
          alert('删除失败，请重试');
        }
      });
    </script>
  </body>
</html>
